<?php
/**
 * User: b179a9
 * Date: 09.09.11
 * Time: 19:14
 */

class DeliveryController extends Zend_Controller_Action
{
    /**
     * FlashMessenger
     *
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;


    function init()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        } else {
            $this->_helper->layout()->setLayout('admin-layout');
        }
        $this->_flashMessenger = new Lib_Flash();
    }

    public function __call($name, $args)
    {
        $this->_forward('index');
    }

    function indexAction()
    {
        $mailManager = new \Managers\Mail();
        $mails = $mailManager->getList();

        $this->view->mails = $mails;
    }

    function addAction()
    {
        $form = new App_Form_User_Delivery();

        if ($this->_request->isPost()) {
            if ($form->isValid($this->_request->getParams())) {
                $preview = $form->getElement('preview')->getValue();
                $message = $form->getElement('text')->getValue();
                $subject = $form->getElement('subject')->getValue();
                if ($preview) {
                    $email_to = \Managers\Mail::ADMIN;
                    \Managers\Mail::sendEmail($message, $email_to, $subject);
                    $this->_flashMessenger->addMessage("Test Email successfully has been sent to admin.",
                                                       Lib_Flash::NOTICE, Lib_Flash::POST);
                } else {
                    $mailsManager = new \Managers\Mail();
                    $mailsManager->add($this->_request->getParams());
                    $this->_flashMessenger->addMessage('Emails will be sent soon.',
                                                       Lib_Flash::NOTICE, Lib_Flash::PRE);
                    $this->_redirect('/admin');
                }
            }
        }

        $this->view->form = $form->render();
    }

    function sendAction()
    {
        $this->_helper->layout()->disableLayout();
        $mailManager = new \Managers\Mail();
        $mails = $mailManager->getNotDelivered();

        $usersManager = new \Managers\Users();

        foreach ($mails as $mail) {

            $users = isset($mail['map']) ? $usersManager->getNotDeliveredByMap($mail['map']) :
                    $usersManager->getNotDelivered();

            foreach ($users as $user) {
                \Managers\Mail::sendEmail($mail['content'], $user['email'], $mail['title']);
                $usersManager->setMailSent($user['id']);
            }

            $mailManager->setStatus($mail['id']);
        }

    }

}
